package com.yoomiito.app.present.account;


import android.text.TextUtils;

import com.yoomiito.app.Constant;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.model.bean.BingPhoneBean;
import com.yoomiito.app.model.bean.GuiMiResult;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.base.BaseAccountPresent;
import com.yoomiito.app.ui.account.InputCodeCheckActivity;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.UserInfoConfig;

import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class InputCodeCheckPresent extends BaseAccountPresent<InputCodeCheckActivity> {
    private static final String TAG = "InputCodeCheckPresent";

    private Disposable mDisposable;

    public InputCodeCheckPresent(AppConfig appConfig) {
        super(appConfig);
    }

    /**
     * 开始倒计时
     */
    public void startCountdownTask() {
        mDisposable = Flowable.intervalRange(0, 45, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> getV().CountdownTimeTask((int) (45 - aLong)))
                .doOnComplete(() -> getV().timeEndTask()).subscribe();
    }

    /**
     * 销毁倒计时任务
     */
    public void destroyCountdownTask() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    /**
     * 发送验证码
     *
     * @param phoneNum
     */
    public void requestSendCode(String phoneNum) {
        getV().showLoading();
        sendCode(phoneNum,"86").subscribe(new ApiSubscriber<BingPhoneBean>(handleException()) {
            @Override
            public void onSuccess(BingPhoneBean bingPhoneBean) {
                getV().dismissLoading();
                getV().showToast("发送成功");
            }

            @Override
            public void onFail(ApiException error) {
                getV().dismissLoading();
//                getV().showToast("发送失败");
            }
        });
    }

    /**
     * 验证验证码
     * 以验证验证码后的获得token为准
     * @param verify_code 验证码
     * @param mobile      手机号
     * @param open_id     微信id
     */
    public void requestVerifyCode(String verify_code, String mobile, String open_id) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        getV().showLoading();
        YmApi.getYmService().verifyCode(verify_code, mobile, open_id)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<UserInfo>getApiTransformerData())
                .compose(XApi.<UserInfo>getScheduler())
                .subscribe(new ApiSubscriber<UserInfo>(handleException()) {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        getV().dismissLoading();
//                        LoginUtils.INSTANCE.loginHandle(getV(),userInfo);
                        if (TextUtils.isEmpty(userInfo.getParent_invitation_code())) {
                            UserInfoConfig.putToken(userInfo.getToken());
                            L.i("Token: "+ SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""));
                            getV().success();//需要绑定邀请码 保存Token
                        } else {
                            getV().toMain(userInfo);//登录成功
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        XLog.d(TAG, "error ：" + "||code:" + error.getCode() + "||msg:" + error.getMsg());
                    }
                });
    }

    /**
     * 以验证验证码后的获得token为准
     *
     * @param id
     * @param phone
     * @param code
     */
    public void sureGuiMiHuiId(String id, String phone, String code) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        getV().showLoading();
        YmApi.getYmService()
                .guimihuiAct(id, phone, code)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<GuiMiResult>(handleException()) {
                    @Override
                    public void onSuccess(GuiMiResult result) {
                        getV().dismissLoading();
                        String token = result.getToken();
                        if (result != null && result.getUser() != null && !TextUtils.isEmpty(result.getUser().getParent_invitation_code())) {//登录成功
                            result.getUser().setToken(token);//
                            getV().guiMIHuiLogin(result);
                        } else {
                            UserInfoConfig.putToken(token);//需要绑定邀请码 保存Token
                            getV().success();
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                    }
                });
    }
}
